package com.fw.util;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

/** 璇ョ被鐢ㄤ簬璁＄畻瀛楃涓叉垨鑰呮枃浠剁殑MD5鍊�
 * 
 * @author 
 * @version 1.0, 2013-1-26 涓嬪崍3:23:23 */
public class MD5Utils {
	private static MD5Utils instance = null;
	private static MessageDigest md5 = null;

	private MD5Utils () {
	};

	/** 鑾峰緱涓�釜瀵硅薄
	 * 
	 * @return
	 * @author 鏉滄槦闇�*/
	public static MD5Utils getInstance () {
		try {
			instance = new MD5Utils();
			md5 = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			return null;
		}
		return instance;
	}

	/** 鑾峰緱涓�釜瀛楃涓茬殑MD5鍊�
	 * 
	 * @param source
	 * @return
	 * @author 鏉滄槦闇�*/
	public String getStringHash (String source) {
		String hash = null;
		try {
			ByteArrayInputStream in = new ByteArrayInputStream(source.getBytes());
			hash = getStreamHash(in);
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hash;
	}

	/** 鑾峰緱涓�釜File鐨凪D5鍊�
	 * 
	 * @param file
	 * @return
	 * @author 鏉滄槦闇�*/
	public String getFileHash (File file) {
		String hash = null;
		try {
			FileInputStream in = new FileInputStream(file);
			hash = getStreamHash(in);
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hash;
	}

	/** 鑾峰緱涓�釜娴佹枃浠剁殑MD5鍊�
	 * 
	 * @param stream
	 * @return
	 * @author 鏉滄槦闇�*/
	public String getStreamHash (InputStream stream) {
		String hash = null;
		byte[] buffer = new byte[1024];
		BufferedInputStream in = null;
		try {
			in = new BufferedInputStream(stream);
			int numRead = 0;
			while ((numRead = in.read(buffer)) > 0) {
				md5.update(buffer, 0, numRead);
			}
			in.close();
			hash = toHexString(md5.digest());
		} catch (Exception e) {
			if (in != null) try {
				in.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			e.printStackTrace();
		}
		return hash;
	}

	/** 灏哹yte鏁版嵁杞寲涓篗D5
	 * 
	 * @param b
	 * @return
	 * @author 鏉滄槦闇�*/
	private String toHexString (byte[] b) {
		StringBuilder sb = new StringBuilder(b.length * 2);
		for (int i = 0; i < b.length; i++) {
			sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
			sb.append(hexChar[b[i] & 0x0f]);
		}
		return sb.toString();
	}

	// 杞寲鍖归厤鏁扮粍
	private char[] hexChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
}
